package cc.booku.owlbox.RsaUtil;

import android.graphics.Color;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.NetPingManager;
import cc.booku.owlbox.R;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import static cc.booku.owlbox.RsaUtil.TestRSA.getPrivateKey;

public class RsaActivity extends AppCompatActivity {

    private Toolbar Toolbar;
    private EditText et_original_text, et_ciphertext;
    private Button bt_res, bt_use, bt_iptest;
    private TextView tv_decrypt, tv_result;
    private String ProfilePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "Profile.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rsa);
        et_ciphertext = (EditText) findViewById(R.id.et_ciphertext);
        et_original_text = (EditText) findViewById(R.id.et_original_text);
        tv_decrypt = (TextView) findViewById(R.id.tv_decrypt);
        tv_result = (TextView) findViewById(R.id.tv_result);
        bt_iptest = (Button) findViewById(R.id.bt_iptest);
        bt_iptest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Message msg = new Message();
                msg.what = 9;
                handler.sendMessage(msg);//用activity中的handler发送消息

            }
        });
        bt_use = (Button) findViewById(R.id.bt_use);
        bt_use.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message msg = new Message();
                msg.what = 14;
                handler.sendMessage(msg);//用activity中的handler发送消息
            }
        });


        bt_res = (Button) findViewById(R.id.bt_res);
        bt_res.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                String rsa = FileoOperations.readAssetsTxt(RsaActivity.this, "TxtData/RSA");
                JSONObject obja = JSONObject.parseObject(rsa);
                String RSA_PUBLIC = obja.getString("RSA_PUBLIC");

                String cipher = et_original_text.getText().toString();

                if (cipher.equals("")) {


                    tv_result.setText("加密结果：" + "\n加密地址为空，请重新输入");

                } else if (!cipher.equals("")) {

                    // if(checkUrl(cipher,400)){
                    // 从字符串中得到公钥
                    PublicKey publicKey = null;
                    try {
                        publicKey = RSAUtils.loadPublicKey(RSA_PUBLIC);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    byte[] encryptByte = RSAUtils.encryptData(cipher.getBytes(), publicKey);
                    // 为了方便观察吧加密后的数据用base64加密转一下，要不然看起来是乱码,所以解密是也是要用Base64先转换
                    String afterencrypt = Base64Utils.encode(encryptByte);

                    et_ciphertext.setText(afterencrypt);
//                   }else {
//
//                       tv_result.setText("加密结果："+"\n加密地址测试连接出错，请检查服务器文件，或者重新输入（完整服务器文档在q群：799921081）");
//                       Log.i("response===========>","加密地址测试连接出错，请重新输入");
//                   }


                }


//                //解密
//                //获取RSA_PRIVATE
//                String jrsa = FileoOperations.readAssetsTxt(RsaActivity.this, "TxtData/RSA");
//                JSONObject obja1 = JSONObject.parseObject(jrsa);
//                String RSA_PRIVATE = obja1.getString("RSA_PRIVATE");
//

//                try
//                {
//                    // 从字符串中得到私钥
//                    PrivateKey privateKey = RSAUtils.loadPrivateKey(RSA_PRIVATE);
//                    // 从文件中得到私钥
//                    // 因为RSA加密后的内容经Base64再加密转换了一下，所以先Base64解密回来再给RSA解密
//                    byte[] decryptByte = RSAUtils.decryptData(Base64Utils.decode(afterencrypt), privateKey);
//                    String decryptStr = new String(decryptByte);
//                    tv_decrypt.setText(decryptStr);
//
//                } catch (Exception e)
//                {
//                    e.printStackTrace();
//                }


            }
        });

        //加载标题栏
        LoadToolbar();
        //状态栏颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));
    }


    public static Boolean checkUrl(String address, int waitMilliSecond) {
        try {
            URL url = new URL(address);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setConnectTimeout(waitMilliSecond);
            conn.setReadTimeout(waitMilliSecond);

            //HTTP connect
            try {
                conn.connect();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            int code = conn.getResponseCode();
            if ((code >= 100) && (code < 400)) {
                return true;
            }

            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 9:

                    String ProfileStr = FileoOperations.readFromSDFile(RsaActivity.this, ProfilePath);
                    //读取配置文件信息
                    JSONObject obj = JSONObject.parseObject(ProfileStr);
                    String testfile = obj.getString("测试地址");

                    // if(checkUrl(et_original_text.getText().toString()+testfile,400)){
                    HttpResponse(et_original_text.getText().toString() + testfile);
//                    }else {
//                        tv_result.setText("测试结果："+"\n地址存在问题，测试结果无法连接");
//
//                    }Log.i("response===========>", et_original_text.getText().toString()+testfile);


//                    if (NetPingManager.ping(res)) {
//                        Log.d("serverTest", "serverTest----" + "服务器在线");
//                        tv_result.setText("测试结果："+"\n服务器在线");
//                    } else {
//                        tv_result.setText("测试结果："+"\n服务器离线暂不可用");
//                    }


                    break;
                case 14:

                    if (!et_ciphertext.getText().toString().equals("")) {


                        SettingProfile("地址密文", et_ciphertext.getText().toString());
                        tv_result.setText("应用结果：" + "\n应用成功");
                    } else {
                        tv_result.setText("应用结果：" + "\n您还没有加密，或者加密地址有问题");
                    }

                    break;

                case 18:
                    String urltest = msg.getData().getString("urltest");//接受msg传递过来的参数

                    if (urltest.equals("owl")) {

                        Log.i("response===========>", urltest);
                        tv_result.setText("测试结果：" + "\n服务器在线,可以尝试应用，如果应用出错，导致程序无法运行，至owldatabase删除profile.txt文件重启软件即可");
                    } else {
                        Log.i("response===========>", urltest);
                        tv_result.setText("测试结果：" + "\n服务器不在线或者服务端程序可能与本程序不符合，强制写入配置文件，可能导致程序出现闪退等情况");

                    }


                    break;


            }
        }
    };


    private void HttpResponse(String url) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String res = response.body().string();
                //Log.i("response===========>",res);

                Message msg = new Message();
                msg.what = 18;
                Bundle bundle2 = new Bundle();
                bundle2.putString("urltest", res);  //往Bundle中存放数据
                msg.setData(bundle2);//mes利用Bundle传递数据
                handler.sendMessage(msg);//用activity中的handler发送消息


            }
        });

    }


    private void LoadToolbar() {
        //新页面接收数据


        Toolbar = (Toolbar) findViewById(R.id.toolbar);

        Toolbar.setTitle("地址加密");

        setSupportActionBar(Toolbar);//利用Toolbar代替ActionBar
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                finish();
            }
        });

    }


    private void SettingProfile(String key, String value) {


        String ProfileStr = FileoOperations.readFromSDFile(this, ProfilePath);
        //读取配置文件信息
        try {


            JSONObject query = JSON.parseObject(ProfileStr);
            query.put(key, value);
            Log.d("修改后完整数据", query.toJSONString());

            //保存到数据文件
            FileoOperations.writeAssignTxt(ProfilePath, query.toJSONString());


        } catch (Exception e) {

            Toast.makeText(RsaActivity.this, "修改配置文件发生错误", Toast.LENGTH_SHORT).show();
//异常处理
        }

    }
}
